package com.xq.utils;

import cn.hutool.core.util.StrUtil;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * 对象工具类
 *
 * @author xu
 * 2021/8/13 10:24
 */
public class ClassUtil {
    /**
     * 将对象属性转换为string 以逗号隔开
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    public static String objectToString(Object obj) throws IllegalAccessException {
        StringBuilder stringBuilder = new StringBuilder();
        // 遍历属性
        for (Field field : obj.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            // 不为空时添加
            if(!StrUtil.isBlankIfStr(fieldName)){
                stringBuilder
                        .append(",")
                        .append(fieldName);
            }
        }
        // 去除第一个 ,
        stringBuilder.delete(0,stringBuilder.indexOf(",")+1);
        return stringBuilder.toString();
    }

    /**
     * 将对象转为map对象 值为空就去除
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, String> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, String> map = new HashMap<>();
        // 遍历
        for (Field field : obj.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            // 值不为空时转换
            if(StrUtil.isBlankIfStr(value)){
                map.put(fieldName, (String) value);
            }
        }
        return map;
    }
}
